/**
 * Initialize page's components and functions.
 */
function initPage(frontEndPath, viewMyOwnBlog) {
    //initColumnHeight();
    initMenu();
    initLink();
    initDialogs(frontEndPath);
    
    // Init sortable
    var col1 = $("#col-1"), col2 = $("#col-2"), colmain = $("#col-main");
    
    if (!viewMyOwnBlog) {
        $(".edit-button").addClass("invisible");
        $(".delete-button").addClass("invisible");
        $("#write-entry").addClass("invisible");
        $("#upload-photo").addClass("invisible");
    } else {
        $("#col-1 .module, #col-2 .module, #col-main .module").addClass("sort");
        $("#col-1, #col-2, #col-main").addClass("sort-session");
        $("#col-1, #col-2, #col-main").sortable({
            placeholder: "place-holder",
            connectWith: ".sort-session"
        });
        $("#col-1, #col-2, #col-main").disableSelection();
    }
}

/**
 * Make the columns in main-content have the same height.
 */
function initColumnHeight() {
    var columns = $("#main-content > div");
    var clearDIVs = $(".clear");
    var maxHeight = 0;
    columns.each(function() {
        if ($(this).outerHeight(true) > maxHeight)
            maxHeight = $(this).outerHeight(true);
    });
    columns.height(maxHeight + 50);
    clearDIVs.height(0);
}

/**
 * Init links if needed.
 */
function initLink() {
    $("#friend-list .person").click(function() {
        var link = $(this).find(".link").html();
        window.location = link;
    });
}

/**
 * Initialize Menu
 */
function initMenu(viewMyOwnBlog) {
	var advanceShowed = false;
	var messageShowed = false;
	var notificationShowed = false;
	var friendRequestShowed = false;
	var txtInput = $('input[name=txtSearch]');
	var btnSubmit = $('#btnSearch');
	var btnShowAdvanceSearch = $('#menu #show-advance');
	var pnlAdvanceSearch = $('#menu #advance');
	var btnShowFriendRequest = $("#show-friend-request");
	var btnShowNotification = $("#show-notification");
	var btnShowMessage = $("#menu #show-message");
	var pnlMessage = $("#menu #message");
	var pnlNotification = $("#menu #notification");
	var pnlFriendRequest = $("#menu #friend-request");
	initSearch();
	
	btnShowNotification.click(function() {
		if(notificationShowed) {
			pnlNotification.hide();
		} else {
			hideAll();
			pnlNotification.show();
		}
		notificationShowed = !notificationShowed;
	})	
		
	btnShowFriendRequest.click(function () {
		if(friendRequestShowed) {
			pnlFriendRequest.hide();
		} else {
			hideAll();
			pnlFriendRequest.show();
		}
		friendRequestShowed = !friendRequestShowed;
	})
	
	btnShowMessage.click(function() {
		if(messageShowed) {
			pnlMessage.hide();
		} else {
			hideAll();
			pnlMessage.show();
		}
		messageShowed = !messageShowed;
	})
	
    btnShowAdvanceSearch.click(function() {	    
	        if(advanceShowed) {
		        pnlAdvanceSearch.hide('slide', {direction: 'up'}, 250);
	        } else {
		        hideAll();
		        pnlAdvanceSearch.show('slide', {direction: 'up'}, 250);
	        }
	        advanceShowed = !advanceShowed;		
    });
		
	/**
	 * Initialize Search area
	 */
	function initSearch() {
		var isActive = false;
		
		function getSearchParameter() {
			if(isActive) {
				return txtInput.val();
			} else {
				return '';
			}
		};
		
		txtInput.focus(function() {
			if(!isActive) {
				isActive = true;
				txtInput.val('');
				txtInput.removeClass('inactive');
				txtInput.addClass('active');
			}
		});
		
		txtInput.focusout(function() {
			if($(this).val() == '') {
				isActive = false;
				$(this).removeClass('active');
				$(this).addClass('inactive');
				$(this).val('Tìm kiếm...');
			};
		});
					
		btnSubmit.click(function() {
		});
	}
	
	/**
	 * Hide all panels.
	 */
	function hideAll() {
		pnlNotification.hide();
		pnlMessage.hide();
		pnlFriendRequest.hide();
		pnlAdvanceSearch.hide();
		notificationShowed = false;
		messageShowed = false;
		advanceShowed = false;
		friendRequestShowed = false;
	}
}

/**
 * Initialize page's dialogs.
 */
function initDialogs(frontEndPath) {
    var loadingHTML = "<div class='loading'></div>";
    var btnChangeLayout = $("#change-layout");
    var btnChangeTheme = $("#change-theme");
    var btnAdvanceSearch = $("#advance-search");
    var btnChangeModule = $("#change-module");
    var btnChangeAlbum = $("#change-album");
    var btnChangeFolder = $("#change-category");
    var btnWriteEntry = $("#write-entry");
    var btnUploadPhoto = $("#upload-photo");
    var dlgUploadPhoto = $("#dialog-photo");
    var dlgWriteEntry = $("#dialog-entry");
    var dlgTheme = $("#dialog-theme");
    var dlgLayout = $("#dialog-layout");
    var dlgAlbum = $("#dialog-album-manager");
    var dlgFolder = $("#dialog-folder-manager");
    var dlgPersonalInfo = $("#dialog-personal-info");
    var dlgModule = $("#dialog-module");
    var dlgBlogInfo = $("#dialog-blog-info");

    initThemeDialog();
    initLayoutDialog();
    initAlbumManagerDialog();
    initFolderManagerDialog();
    initPersonalInfoDialog();
    initModuleDialog();
    initEntryDialog();
    initPhotoDialog();
    initBlogInfoDialog();
    //btnUploadPhoto.tooltip();
    //btnWriteEntry.tooltip();

    /**
     * Init Change-Theme dialog.
     */
    function initBlogInfoDialog(){
           dlgBlogInfo.dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });

        $("#info .edit-toolbar .edit-button").click(function() {
            dlgBlogInfo.dialog("open");
            dlgBlogInfo.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/BlogInfo.aspx',
                success: function(data) {
                    dlgBlogInfo.html(data);
                }
            });
        });
    
    }
    function initThemeDialog() {
        dlgTheme.dialog({
            autoOpen: false,
            width: 700,
            height: 550,
            modal: true,
            buttons: {
                "Xong": function() {
                    saveChange();
                    $(this).dialog("close");
                    $(this).html("");
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                    $(this).html("");
                }
            }
        });

        btnChangeTheme.click(function() {
            dlgTheme.dialog("open");
            dlgTheme.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/ChangeTheme.aspx',
                success: function(data) {
                    dlgTheme.html(data);
                    initDialog();
                }
            });
        });
    }

    /**
    * Init Change-Layout dialog.
    */
    function initLayoutDialog() {
        dlgLayout.dialog({
            autoOpen: false,
            width: 700,
            height: 550,
            modal: true,
            buttons: {
                "Xong": function() {
                    saveChange();
                    $(this).dialog("close");
                    $(this).html("");
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                    $(this).html("");
                }
            }
        });

        btnChangeLayout.click(function() {
            dlgLayout.dialog("open");
            dlgLayout.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/ChangeLayout.aspx',
                success: function(data) {
                    dlgLayout.html(data);
                    initDialog();
                }
            });
        });
    }

    /**
    * Init Album-Manager dialog.
    */
    function initAlbumManagerDialog() {
        dlgAlbum.dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });

        btnChangeAlbum.click(function() {
            dlgAlbum.dialog("open");
            dlgAlbum.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/AlbumManager.aspx',
                success: function(data) {
                    dlgAlbum.html(data);
                }
            });
        });
    }

    /**
    * Init Folder-Manager dialog.
    */
    function initFolderManagerDialog() {
        dlgFolder.dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });

        btnChangeFolder.click(function() {
            dlgFolder.dialog("open");
            dlgFolder.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/FolderManager.aspx',
                success: function(data) {
                    dlgFolder.html(data);
                }
            });
        });
    }

    /**
    * Init Personal-Info dialog.
    */
    function initPersonalInfoDialog() {
        dlgPersonalInfo.dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });
    }

    /**
    * Init Module dialog.
    */
    function initModuleDialog() {
        dlgModule.dialog({
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });

        btnChangeModule.click(function() {
            dlgModule.dialog("open");
            dlgModule.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/SelectModule.aspx',
                success: function(data) {
                    dlgModule.html(data);
                }
            });
        });
    }

    /**
    * Init Entry dialog.
    */
	function closeDialog(){
		$('.my-popup').fadeOut(300 , function() {
			$('#mask').fadeOut(300);
		}); 
		return false;
	}	
    function showDialog(id){
		var popupBox = id;
		// Add the mask to body
		$('#container').append('<div id="mask"></div>');
		$('#mask').fadeIn(300);	
		//Fade in the Popup
		$(popupBox).fadeIn(300);
		
		//Set the center alignment padding + border see css style
		
		$(popupBox).css({
			'position': 'absolute',	
			'width':936,
			'margin-top':$(window).scrollTop()+25,
			'margin-right':50,			
		});
		
			
		return false;
	} 
    function initEntryDialog() {       
		dlgWriteEntry.append('');
		dlgWriteEntry.append('<div class="ct"></div>');		
        btnWriteEntry.click(function() {
			//dlgWriteEntry.find("div.ct").html(loadingHTML);			
			$.ajax({
                type: 'GET',
                url: frontEndPath + 'Dialog/EntryDetail.aspx',
                success: function(data) {				
                    dlgWriteEntry.find("div.ct").html(data);						
					showDialog("#dialog-entry"); 
					var instance = CKEDITOR.instances["entry_content"];
					if(instance){							
						CKEDITOR.remove(instance);						
					}
					$( ".datepicker" ).datepicker({showOn: "button",showAnim: "slideDown",numberOfMonths: 1,showButtonPanel: true});
					
					CKEDITOR.replace( 'entry_content',
					{
						toolbar :
						[
							{ name: 'document', items : [ 'Source','-','NewPage','DocProps','Preview','Print','-','Templates' ] },
							{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },							
							{ name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton','Table', 
								'HiddenField' ] },
							'/',
							{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
							{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
							'-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
							{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },							
							'/',
							{ name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
							{ name: 'colors', items : [ 'TextColor','BGColor' ] },
							{ name: 'insert', items : [ 'Image','Flash','Smiley','SpecialChar'] },
							{ name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
						],
						width:760
					});		
                }
            });
        });
        dlgWriteEntry.delegate('.my-popup a.close_pop','click', function() { 
			closeDialog();
			return false;
		});
		dlgWriteEntry.delegate('#btn_add_category','click', function() {
			var pos = $(this).position();				
			$('<div><form><input type="text" name="category_name"/></form></div>').dialog({				
				height: 200,
				width: 300,
				position: [pos.left+100,pos.top],
				modal: true,
				hide: "explode",
				buttons: {
					"Save": function() {
						var category_name = $(this).find("form input[name='category_name']").val();						
						
						if(category_name ==""){
							return;
						}
						
						postCategoryData(category_name);
						$(this).dialog("close");	
					},
					"Cancel": function() {
						$(this).dialog("close");	
					}
				}
			});
			return false;
		});
		dlgWriteEntry.delegate('button#entry_post','click',function(){			
			CKEDITOR.instances['entry_content'].updateElement();
			$('span.error-tip').remove();
			var validate = validateEntry($("#frm_entry"));			
			if(validate == true){				
				var data = $("#frm_entry").serialize();
				data +="&action=ENTRY";
				dlgWriteEntry.find("div.ct").html(loadingHTML);
				postEntryData(data);
			}			
		});
		$("button#entry_cancel").live('click',function(){
			closeDialog();
		});
		function postEntryData(data){    
			$.ajax({
				type:'POST',
				url: frontEndPath + 'Dialog/EntryDetail.aspx',
				data:data,
				success: function(msg){
					if(msg=="true"){
						alert("Ye");
					}
				}
			});
		}
		function postCategoryData(category_name){    
			$.ajax({
				type:'POST',
				url: frontEndPath + 'Dialog/EntryDetail.aspx',
				data:{
					category_name :category_name,
					action : 'CATEGORY'
				},
				success: function(inserted_id){					
					if(inserted_id!="0"){
						$("select#entry_category").append("<option selected value="+inserted_id+">"+category_name+"</option>");
					}
				}
			});
		}
		
		function validateEntry(form){
			var arr_input = form.find('input');
			var arr_select = form.find('select');
			var validate = true;
			arr_input.each(function(index){
				var input = $(this);
				if(input.hasClass('require') && input.val()==""){									
					input.css("border","1px solid red");
					addErrorTip(input,"không được bỏ trống!");
					input.focus();					
					validate = false;
				}
			});
			arr_select.each(function(index){				
				var select = $(this);				
				if(select.hasClass('require') && select.val()==null){										
					select.css("border","1px solid red");
					addErrorTip(select,"không được bỏ trống!");
					select.focus();					
					validate = false;
				}
			});
			return validate;
		}
		
		function addErrorTip(element,error){
			var span = '&nbsp;<span class="error-tip">'+error+'</span>';
			element.parent().append(span);			
		}
	}

    /**
    * Init Upload-Photo dialog.
    */
    function initPhotoDialog() {
        dlgUploadPhoto.dialog({        
            autoOpen: false,
            width: 800,
            height: 600,
            modal: true,
            buttons: {
                "Xong": function() {
                },
                "Hủy bỏ": function() {
                    $(this).dialog("close");
                }
            }
        });

        btnUploadPhoto.click(function() {
            dlgUploadPhoto.dialog("open");
            dlgUploadPhoto.html(loadingHTML);
            $.ajax({
                type: 'POST',
                url: frontEndPath + 'Dialog/UploadPhoto.aspx',
                success: function(data) {
                    dlgUploadPhoto.html(data);
                }
            });
        });
    }
}